package org.noote.libs.tcpip.helper;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.util.Log;
import android.widget.Toast;

public class Helper_WiFi {
	private static final String LOG_TAG = "Helper_WiFi";	

	public static String getCurrentIPAddress_WiFi_Only(final Activity activity, boolean bAskConnect) {
		WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
		
		if (!wifiManager.isWifiEnabled()) {
			Log.e(LOG_TAG, "No WiFi found");

			if (bAskConnect) {
				new AlertDialog.Builder(activity)
						.setTitle("Try to enable WiFi ?")
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int whichButton) {
										WifiManager wifiManager = (WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
										try {
											if(!wifiManager.isWifiEnabled())
												wifiManager.setWifiEnabled(true);
											Log.e(LOG_TAG, "WiFi enabled...");
										} catch (Exception e) {
											Log.e(LOG_TAG, "Exception catch : "
													+ e.toString());
										}
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int whichButton) {
										Toast.makeText(
												activity.getApplicationContext(),
												"Please active WiFi manually !",
												Toast.LENGTH_LONG).show();
									}
								}).show();
			} else
				Toast.makeText(activity.getApplicationContext(),
						"No WiFi found. Please active it !", Toast.LENGTH_LONG)
						.show();

			return "";
		}
		
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if(wifiInfo.getSupplicantState() != SupplicantState.COMPLETED)
		{
			Toast.makeText(activity.getApplicationContext(),
					"WiFi not yet connected. Please connect it !", Toast.LENGTH_LONG)
					.show();
			return "";
		}
		int ipAddress = wifiInfo.getIpAddress();
		if(ipAddress==0) return "";
		
		return Formatter.formatIpAddress(ipAddress);
	}
}
